var WebIM = require('../../utils/WebIM.js')
var WebIM = WebIM.default
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    chatMsg: [],
    emojiStr: '',
    yourname: '',
    myName: '',
    password: '',
    sendInfo: '',
    userMessage: '',
    inputMessage: '',
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    show: false,
    isPic: true,
    view: 'scroll_view',
    toView: '',
    emoji: WebIM.Emoji,
    emojiObj: WebIM.EmojiObj,
    selfNickname: '',
    selfHeadImgUrl: '',
    yourNickname: '',
    yourHeadImgUrl: '',
  },
  /**
   * 生命周期函数--监听页面加载
   */
  hxloign: function () {
    var options = {
      apiUrl: WebIM.config.apiURL,
      user: this.data.myName,
      pwd: this.data.password,
      grant_type: 'password',
      appKey: WebIM.config.appkey
    }
    WebIM.conn.open(options)
  },
  setChatMemberListCache() {
    const myName = this.data.myName;
    let chatMemberList = wx.getStorageSync('chatMemberList') || [];
    let chatMemberName = 'from' + this.data.yourname + 'to' + myName;
    if (!chatMemberList.includes(chatMemberName)) {
      chatMemberList.push(chatMemberName);
    }
    wx.setStorage({
      key: 'chatMemberList',
      data: chatMemberList
    })
  },

  sendMessage() {
    var that = this;
    if (!this.data.userMessage.trim()) return;
    var myName = this.data.myName;
    var id = WebIM.conn.getUniqueId();
    var msg = new WebIM.message('txt', id);
    msg.set({
      msg: that.data.userMessage,
      to: that.data.yourname,
      roomType: false,
      // 携带自己的头像和昵称
      ext: {
        time: WebIM.time(),
        nickname: that.data.selfNickname,
        headImgUrl: that.data.selfHeadImgUrl
      },
      success: (res) => {
        console.log("发送的信息为:", res)
      },
      fail: (res) => {
        console.log('你是个大傻逼', res)
      }
    });
    msg.body.chatType = 'singleChat';
    
    WebIM.conn.send(msg.body);

    console.log('发送xmpp消息', msg);

    if (msg) {
      var value = WebIM.parseEmoji(msg.value.replace(/\n/mg, ''));
      var time = WebIM.time();
      var msgData = {
        info: {
          to: msg.body.to
        },
        myName: myName,
        yourname: msg.body.to,
        msg: {
          type: msg.type,
          data: value
        },
        style: 'self',
        time: time,
        mid: msg.id,
      };

      that.data.chatMsg.push(msgData);

      const chatMsgCache = {
        yourNickname: that.data.yourNickname,
        yourHeadImgUrl: that.data.yourHeadImgUrl,
        yourname: that.data.yourname,
        chatMsg: that.data.chatMsg
      }

      wx.setStorage({
        key: 'from' + that.data.yourname + 'to' + myName,
        data: chatMsgCache,
        success: function () {
          that.setData({
            chatMsg: that.data.chatMsg,
            emojiList: [],
            inputMessage: ''
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
      })
      that.setData({
        userMessage: '',
        show: '',
        view: '',
        isPic: true
      })
    }
    that.setChatMemberListCache();
  },
  receiveMsg: function (msg, type) {
    var that = this;
    var myName = this.data.myName;
    if (msg.from == that.data.yourname || msg.to == that.data.yourname) {
      if (type == 'txt') {
        var value = WebIM.parseEmoji(msg.data.replace(/\n/mg, ''))
      } else if (type == 'emoji') {
        var value = msg.data
      }
      console.log('nowdata',msg);
      var time = msg.ext.time;
      var msgData = {
        info: {
          from: msg.from,
          to: msg.to
        },
        myName: msg.from,
        yourname: msg.to,
        msg: {
          type: type,
          data: value,
          url: msg.url
        },
        style: '',
        time: time,
        mid: msg.type + msg.id
      };
      if (msg.from == that.data.yourname) {
        msgData.style = '';
        msgData.myName = msg.from;
      } else {
        msgData.style = 'self';
        msgData.yourname = msg.to;
      }
      console.log('chat.js')
      that.data.chatMsg.push(msgData);
      const chatMsgCache = {
        yourNickname: that.data.yourNickname || msg.ext.nickname,
        yourHeadImgUrl: that.data.yourHeadImgUrl || msg.ext.headImgUrl,
        yourname: that.data.yourname,        
        chatMsg: that.data.chatMsg
      };
      wx.setStorage({
        key: 'from' + that.data.yourname + 'to' + myName,        
        data: chatMsgCache,
        success: function () {
          if (type == 'audio') return;
          that.setData({
            chatMsg: that.data.chatMsg,
            emojiList: [],
            inputMessage: ''
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
      })
      that.setChatMemberListCache();
    }
  },
  receiveImage(msg, type) {
    var that = this;
    var myName = this.data.myName;
    if (msg) {
      var time = msg.ext.time;
      var msgData = {
        info: {
          from: msg.from,
          to: msg.to
        },
        myName: msg.from,
        yourname: msg.to,
        msg: {
          type: 'img',
          data: msg.url
        },
        style: '',
        time: time,
        mid: 'img' + msg.id
      }

      that.data.chatMsg.push(msgData);

      const chatMsgCache = {
        yourNickname: that.data.yourNickname || msg.ext.nickname,
        yourHeadImgUrl: that.data.yourHeadImgUrl || msg.ext.headImgUrl,
        yourname: that.data.yourname,
        chatMsg: that.data.chatMsg
      };

      wx.setStorage({
        key: 'from' + that.data.yourname + 'to' + myName,   
        data: chatMsgCache,
        success: function () {
          that.setData({
            chatMsg: that.data.chatMsg
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
      })

      that.setChatMemberListCache();
    }
  },
  bindMessage(e) {
    console.log('bindMessage');
    this.setData({
      userMessage: e.detail.value
    })
  },

  cleanInput() {
    console.log('cleanInput')
    var setUserMessage = {
      sendInfo: this.data.userMessage,
      isPic: true      
    }
    this.setData(setUserMessage)
  },
  focus() {
    console.log('focus');
    this.setData({
      show: false,
      view: '',
      isPic: false
    })
  },
  blur(e) {
    if(!e.detail.value){
      this.setData({
        isPic: true
      })
    }
  },
  openEmoji() {
    this.setData({
      show: true,
      isPic: false,
      view: 'scroll_view_change'
    })
  },

  sendEmoji(event) {
    var emoji = event.target.dataset.emoji;
    var msglen = this.data.userMessage.length - 1;
    if (emoji && emoji != '[del]') {
      var str = this.data.userMessage + emoji;
    } else if (emoji == '[del]') {
      var start = this.data.userMessage.lastIndexOf('[');
      var end = this.data.userMessage.lastIndexOf(']');
      var len = end - start;
      if (end != -1 && end == msglen && len >= 3 && len <= 4) {
        var str = this.data.userMessage.slice(0, start)
      } else {
        var str = this.data.userMessage.slice(0, msglen)
      }
    }
    this.setData({
      userMessage: str,
      inputMessage: str
    })
  },
  sendImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: (res) => {
        this.upLoadImage(res, this);
      }
    })
  },
  upLoadImage(res, that) {
    var tempFilePaths = res.tempFilePaths;
    wx.getImageInfo({
      src: res.tempFilePaths[0],
      success: function (res) {
        var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true
        };
        var str = WebIM.config.appkey.split('#');
        var width = res.width;
        var height = res.height;
        var index = res.path.lastIndexOf('.');

        if (index != -1) {
          var filetype = res.path.slice(index + 1)
        }
        if (filetype.toLowerCase() in allowType) {
          wx.uploadFile({
            url: 'https://a1.easemob.com/' + str[0] + '/' + str[1] + '/chatfiles',
            filePath: tempFilePaths[0],
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data'
            },
            success: function (res) {
              var data = res.data
              var dataObj = JSON.parse(data)
              var id = WebIM.conn.getUniqueId();                   // 生成本地消息id
              var msg = new WebIM.message('img', id);
              var file = {
                type: 'img',
                size: {
                  width: width,
                  height: height
                },
                'url': dataObj.uri + '/' + dataObj.entities[0].uuid,
                'filetype': filetype,
                'filename': tempFilePaths[0]
              };

              // 接收消息对象
              var option = {
                apiUrl: WebIM.config.apiURL,
                body: file,
                to: that.data.yourname,
                roomType: false,
                chatType: 'singleChat',
                // 携带自己的头像和昵称
                ext: {
                  time: WebIM.time(),
                  nickname: that.data.selfNickname,
                  headImgUrl: that.data.selfHeadImgUrl
                }
              };

              msg.set(option);
              WebIM.conn.send(msg.body);

              console.log('发送图片消息', msg);

              if (msg) {
                var time = WebIM.time();
                var msgData = {
                  info: {
                    to: msg.body.to
                  },
                  myName: that.data.myName,
                  yourname: msg.body.to,
                  msg: {
                    type: msg.type,
                    data: msg.body.body.url,
                    size: {
                      width: msg.body.body.size.width,
                      height: msg.body.body.size.height,
                    }
                  },
                  style: 'self',
                  time: time,
                  mid: msg.id
                }

                that.data.chatMsg.push(msgData);

                const chatMsgCache = {
                  yourNickname: that.data.yourNickname,
                  yourHeadImgUrl: that.data.yourHeadImgUrl,
                  yourname: that.data.yourname,                  
                  chatMsg: that.data.chatMsg
                };

                var myName = that.data.myName;

                wx.setStorage({
                  key: 'from' + that.data.yourname + 'to' +myName,
                  data: chatMsgCache,
                  success: function () {
                    that.setData({
                      chatMsg: that.data.chatMsg
                    })

                    setTimeout(function () {
                      that.setData({
                        toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
                      })
                    }, 10)
                  }
                })
                that.setChatMemberListCache();
              }
            }
          })
        }
      }
    })
  },
  onLoad: function (options) {
    let yourname = options.id+'';
    let yourHeadImgUrl = options.yourHeadImgUrl;
    let yourNickname = options.yourNickname;
    let myUserInfo = wx.getStorageSync('userInfo');
    wx.setNavigationBarTitle({
      title: yourNickname
    });
    this.setData({
      yourname: yourname,
      myName: myUserInfo.userId+'',
      selfHeadImgUrl: myUserInfo.avatarUrl,
      selfNickname: myUserInfo.userName,
      password: myUserInfo.password,
      yourHeadImgUrl: yourHeadImgUrl,
      yourNickname: yourNickname
    })
    console.log(myUserInfo);
    this.hxloign();
    let chatMsgCache = [];
    let num = '';
    let storyName = 'from' + this.data.yourname + "to" + this.data.myName;
    if (!!wx.getStorageSync(storyName)) {
      chatMsgCache = wx.getStorageSync(storyName).chatMsg || [];
      num = chatMsgCache.length - 1;
    }
    if (num > 0) {
      setTimeout(() => {
        this.setData({
          toView: chatMsgCache[num].mid
        })
      }, 10)
    }
    this.setData({
      inputMessage: '',
      chatMsg: chatMsgCache,
    })
  },
  onShow: function () {
    // wx.onSocketClose(() => {
    //   WebIM.conn.close();
    //   this.hxloign();
    //   console.log("chat页面重新登陆")
    // })
  },
  previewImage(event) {
    var url = event.target.dataset.url
    wx.previewImage({
      urls: [url]  // 需要预览的图片http链接列表
    })
  },
})